<template>
  <div class="ygseyt">
    <h1>员工管理</h1>
    <!-- 查询（重置，搜索） -->
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right" type="primary" @click="onSubmit()" size="small">查询搜索</el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        >重置</el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <!-- <el-form-item label>
            <el-select v-model="value" clearable placeholder="请选择">
              <el-option
                v-for="item in formInline.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item label="搜索内容">
            <el-input v-model="formInline.search" placeholder="请输入员工姓名以查询"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 数据列表（新增员工） -->
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="addyg" style="float:right">新增员工</el-button>
    </el-card>
    <!-- 表格数据 -->
    <div class="table-container">
      <el-table :data="currentData" border style="width: 100%" highlight-current-row>
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="storeName" label="部门"></el-table-column>
        <el-table-column prop="jobName" label="职位"></el-table-column>
        <el-table-column prop="baseSalary" label="薪水"></el-table-column>
        <el-table-column prop="tel" label="电话"></el-table-column>
        <el-table-column label="操作" width="160px">
          <!-- 通过 Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据 -->
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        background
        hide-on-single-page
        layout="prev, pager, next"
        :total="pageNum"
        :page-size="xuanyan.pageSize"
        :pager-count="xuanyan.pageCount"
        @current-change="changePage"
        :current-page="xuanyan.currentPage"
      ></el-pagination>
    </div>
    <!-- 编辑Dialog -->
    <el-dialog
      title="编辑员工信息"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      placeholder="aaa"
    >
      <el-form
        :model="bjRuleForm"
        :rules="rules"
        ref="bjRuleForm"
        label-width="100px"
        class="demo-bjRuleForm"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="bjRuleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-radio-group v-model="bjRuleForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="职位：">
          <el-select v-model="zwValue" clearable placeholder="请选择职位">
            <el-option
              v-for="(item,index) in zwOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证：" prop="idCard">
          <el-input v-model="bjRuleForm.idCard"></el-input>
        </el-form-item>
        <el-form-item label="工资：" prop="baseSalary">
          <el-input v-model="bjRuleForm.baseSalary"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="bjRuleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="电话：" prop="tel">
          <el-input v-model="bjRuleForm.tel"></el-input>
        </el-form-item>
        <el-form-item label="修改日期：" prop="updateTime">
          <el-input v-model="bjRuleForm.updateTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新人：" prop="updateBy">
          <el-input v-model="bjRuleForm.updateBy" disabled></el-input>
        </el-form-item>
        <el-form-item>
          <!-- <el-button @click="resetForm('bjRuleForm')">重 置</el-button> -->
          <el-button type="primary" @click="submitForm('bjRuleForm')">确定修改</el-button>
           <el-button @click="closeDao">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新增Dialog -->
    <el-dialog
      title="新增员工"
      :visible.sync="dialogVisible2"
      width="30%"
      :before-close="handleClose"
      placeholder="aaa"
    >
      <el-form
        :model="xzRuleFrom"
        :rules="bjRules"
        ref="xzRuleFrom"
        label-width="100px"
        class="demo-xzRuleFrom"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="xzRuleFrom.name" placeholder="请输入员工姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-radio-group v-model="xzRuleFrom.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="编号：" prop="number">
          <el-input v-model="xzRuleFrom.number"></el-input>
        </el-form-item>
        <el-form-item label="身份证：" prop="idCard">
          <el-input v-model="xzRuleFrom.idCard"></el-input>
        </el-form-item>
        <el-form-item label="职位：">
          <el-select v-model="zwValue" clearable placeholder="请选择职位">
            <el-option
              v-for="(item,index) in zwOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限：">
          <el-select v-model="qxValue" clearable placeholder="请选择权限">
            <el-option
              v-for="(item,index) in qxOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="薪水：" prop="baseSalary">
          <el-input v-model="xzRuleFrom.baseSalary"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="xzRuleFrom.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="电话：" prop="tel">
          <el-input v-model="xzRuleFrom.tel"></el-input>
        </el-form-item>
        <el-form-item label="更新时间：" prop="createTime">
          <el-input v-model="xzRuleFrom.createTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新人：" prop="updateBy">
          <el-input v-model="xzRuleFrom.createBy" disabled></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm('xzRuleFrom')">重 置</el-button>
          <el-button type="primary" @click="submitxzForm2('xzRuleFrom')">确认添加</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDao">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState } from "vuex";
import * as url from "./../../http/api";
import axios from "../../http/http";
export default {
  name: "ygSet",
  data() {
    return {
      // 搜索
      formInline: {
        search: ""
        // options: [
        //   {
        //     value: "姓名",
        //     label: "姓名"
        //   },
        //   {
        //     value: "职位",
        //     label: "职位"
        //   }
        // ]
      },
      // value: "",
      // -------------------编辑员工
      // Dialog对话框
      dialogVisible: false,
      bjRuleForm: {
        id: "",
        name: "",
        sex: "",
        storeId: "",
        jobId: "",
        baseSalary: "",
        password: "",
        tel: "",
        updateBy: "",
        idCard: "",
        updateTime: ""
      },
      rules: {
        name: [
          { required: false, message: "请输入活动名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        idCard: [
          { required: false, message: "请输入身份证", trigger: "blur" },
          { min: 18, max: 18, message: "请输入18位身份证", trigger: "blur" }
        ],
        tel: [
          { required: false, message: "请输入联系电话", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位联系电话", trigger: "blur" }
        ],
        zwValue: [
          { required: true, message: "请选择职位", trigger: "blur" },
          { min: 2, max: 11, message: "职位不能位空", trigger: "blur" }
        ]
      },
      // 职位
      zwOptions: [],
      zwValue: "",
      // -------------------新增员工
      dialogVisible2: false,
      xzRuleFrom: {
        name: "",
        password: "",
        sex: null,
        idCard: "",
        storeId: 1,
        jobId: null,
        number: "",
        tel: "",
        baseSalary: "",
        createBy: "",
        createTime: "",
        roleId: ""
      },
      bjRules: {
        name: [
          { required: true, message: "请输入员工姓名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入员工密码", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "请输入身份证", trigger: "blur" },
          { min: 18, max: 18, message: "请输入18位身份证", trigger: "blur" }
        ],
        tel: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位联系电话", trigger: "blur" }
        ],
        number: [
          { required: true, message: "请输入员工编号", trigger: "blur" },
          { min: 1, max: 8, message: "最大长度8", trigger: "blur" }
        ]
      },
      // 权限
      qxOptions: [],
      qxValue: "",
      // 表格渲染及分页
      xuanyan: {
        currentPage: 1, //当前页
        pageSize: 8, //显示数据条数
        pageCount: 7 //页码最大显示数
      }
    };
  },
  computed: {
    // 渲染表格数据
    ...mapState({
      yglist: function(state) {
        return state.hpStore.yglist;
      },
      ygjob: function(state) {
        return state.hpStore.ygjob;
      },
      ygstore: function(state) {
        return state.hpStore.ygstore;
      }
    }),
    currentData() {
      let start = (this.xuanyan.currentPage - 1) * this.xuanyan.pageSize;
      let end = this.xuanyan.currentPage * this.xuanyan.pageSize;
      let myjob = this.ygjob;
      let mystore = this.ygstore;
      //男女转化---部门转化
      this.yglist.forEach(item => {
        item.sex == 1 ? (item.sex = "男") : (item.sex = "女");
        for (let i = 0; i < mystore.length; i++) {
          if (mystore[i] !== undefined) {
            if (item.id == mystore[i].id) {
              item.storeName = mystore[i].storeName;
              return;
            } else {
              item.storeName = "暂无部门";
            }
          }
        }
      });
      // 职位转化
      this.yglist.forEach(item => {
        for (let j = 0; j < myjob.length; j++) {
          if (item.id == myjob[j].id) {
            item.jobName = myjob[j].jobName;
            return;
          } else {
            item.jobName = "暂无职位";
          }
        }
      });
      // console.log(myjob);
      return this.yglist.slice(start, end);
    },
    pageNum() {
      return this.yglist.length;
    },
    // 获得登录者姓名
    ...mapGetters(["getName"])
  },
  // -------------------------------------------------------------------------------------------------
  methods: {
    ...mapActions(["ygData", "ygAtherData", "upYgData", "qxData"]),
    // 获取日期
    CurentTime() {
      var now = new Date();
      var year = now.getFullYear(); //年
      var month = now.getMonth() + 1; //月
      var day = now.getDate(); //日
      // var hh = now.getHours(); //时
      // var mm = now.getMinutes(); //分
      // var ss = now.getSeconds(); //秒
      var clock = year + "-";
      if (month < 10) clock += "0";
      clock += month + "-";
      if (day < 10) clock += "0";
      clock += day;
      // if (hh < 10) clock += "0";
      // clock += hh + ":";
      // if (mm < 10) clock += "0";
      // clock += mm + ":";
      // if (ss < 10) clock += "0";
      // clock += ss;
      return clock;
    },
    // -----------------------------------------------查询（后端有误）
    // 查询  (需要发起请求)
    onSubmit() {
      if (this.formInline.search) {
        let obj = {};
        obj.inputValue = this.formInline.search;
        // console.log(obj);
        //这里发起axios请求
        this.$axios({
          url: url.SELYGONLY,
          data: obj,
          method: "post"
        }).then(res => {
          // console.log(res);
          if (res.data.length == 0) {
            this.$message({
              message: "没有该员工",
              type: "warning"
            });
          } else {
            this.upYgData(res.data);
            this.ygAtherData();
          }
        });
      } else {
        if (!this.formInline.search) {
          this.$message({
            message: "搜索内容不能为空，请重试！",
            type: "warning"
          });
        }
      }
    },
    // 查询重置  已完成
    handleResetSearch() {
      this.value = "";
      this.formInline.search = "";
      this.ygData();
      this.ygAtherData();
    },
    // 删除员工 完成
    handleDelete(index, row) {
      this.$confirm("删除后不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let obj = {
            id: row.id,
            name: row.name
          };
          // console.log(obj);
          // 这里发起axios请求（提示删除是否成功）
          this.$axios({
            url: url.DELYG,
            method: "post",
            data: obj
          }).then(res => {
            if (res.data.status === "success") {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.ygData();
              this.ygAtherData();
            } else {
              this.$message({
                type: "error",
                message: "删除失败!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //动态渲染职位下拉列表
    selectList() {
      let zw = this.$store.state.hpStore.zwlist;
      zw.forEach(item => {
        this.zwOptions.push({ value: item.jobName, label: item.jobName });
      });
    },
    //动态渲染权限下拉列表
    seclectQxList() {
      let qx = this.$store.state.hpStore.qxlist;
      qx.forEach(item => {
        this.qxOptions.push({ value: item.name, label: item.name });
      });
    },
    // ------------------------------------------------编辑(已完成)
    handleEdit(index, row) {
      this.dialogVisible = true;
      // this.bjRuleForm = row;
      for (let key in this.currentData[index]) {
        if (this.bjRuleForm[key] != undefined) {
          this.bjRuleForm[key] = this.currentData[index][key];
        }
      }
      this.bjRuleForm.updateBy = this.$store.state.user.name; //操作者
      this.bjRuleForm.storeId = row.storeId; //初始部门id
      this.zwValue = row.storeName; //初始部门名称
      this.selectList();
      this.bjRuleForm.updateTime = this.CurentTime();
      // console.log(this.bjRuleForm);
    },
    // 编辑提交事件(缺少请求接口)
    submitForm(formName) {
      this.bjRuleForm.sex == "男"
        ? (this.bjRuleForm.sex = 1)
        : (this.bjRuleForm.sex = 2);

      let zw = this.$store.state.hpStore.zwlist;
      console.log(zw);
      zw.forEach(item => {
        if (this.zwValue == item.jobName) {
          this.bjRuleForm.jobId = item.id;
          return;
        }
      });
      let obj = {};
      Object.assign(obj, this.bjRuleForm);
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log(obj);
          axios({
            url: url.UPYG,
            method: "post",
            data: obj
          }).then(res => {
            if (res.data.status == "success") {
              this.$message({
                type: "success",
                message: "编辑成功!"
              });
              this.ygData();
              this.ygAtherData();
              this.closeDao();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 编辑重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // -------------------------------------------------添加(后端有误)
    addyg() {
      this.xzRuleFrom.createBy = this.$store.state.user.name;
      this.dialogVisible2 = true;
      this.selectList(); //职位列表
      this.seclectQxList(); //权限列表
      this.xzRuleFrom.createTime = this.CurentTime();
    },
    // 新增提交事件(缺少请求接口)
    submitxzForm2(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.zwValue && this.qxValue) {
            this.xzRuleFrom.sex == "男"
              ? (this.xzRuleFrom.sex = 1)
              : (this.xzRuleFrom.sex = 2);
            // 职位名称与id绑定
            let zw = this.$store.state.hpStore.zwlist;
            zw.forEach(item => {
              if (this.zwValue == item.jobName) {
                this.xzRuleFrom.jobId = item.id;
              }
            });
            // 权限名称与id绑定
            let qx = this.$store.state.hpStore.qxlist;
            qx.forEach(item => {
              if (this.qxValue == item.name) {
                this.xzRuleFrom.roleId = item.id;
              }
            });
            let obj = {};
            Object.assign(obj, this.xzRuleFrom);
            obj.payState = "是";
            console.log(obj);
            axios({
              url: url.ADDYG,
              method: "post",
              data: obj
            }).then(res => {
              console.log(res);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 更改页码
    changePage(val) {
      this.xuanyan.currentPage = val;
    },
    // 关闭dao
    closeDao() {
      this.dialogVisible = false;
      this.dialogVisible2 = false;
      this.zwValue = "";
      this.zwOptions = [];
      this.qxValue = "";
      this.qxOptions = [];
    },
    // 关闭Dialog2
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          this.zwValue = "";
          this.zwOptions = [];
          this.qxValue = "";
          this.qxOptions = [];
        })
        .catch(_ => {});
    }
  },
  created() {
    this.ygData();
    this.ygAtherData();
    this.qxData();
  }
};
</script>

<style scoped lang="less">
.operate-container {
  margin: 15px 0;
}
.block {
  position: absolute;
  left: 50%;
  bottom: 0%;
}
</style>